import paramiko
import os
from scp import SCPClient

def command_log(std):
    stdin, stdout, stderr = std
    # 读取命令输出
    output = stdout.read().decode()
    
    print('执行:', output)


def clear():
    command_log(ssh.exec_command(f"rm -rf {server_folder}/*"))
    command_log(ssh.exec_command(f"docker-compose -p {image_prefix} down"))
 
def scp_upload_folder(local_folder, remote_folder, scp):
    ''''sftp上传文件夹'''
    for item in os.listdir(local_folder):
        local_file_path = os.path.join(local_folder, item)
        remote_file_path = os.path.join(remote_folder, item)
        print(local_file_path)
        print(remote_file_path)
        if os.path.isdir(local_file_path):
            try:
                ssh.exec_command(f'mkdir {remote_file_path}')
            except Exception:
                pass
            scp_upload_folder(local_file_path, remote_file_path, scp)
        else:
            print(f"scp -> {local_file_path}")
            scp.put(local_file_path, remote_file_path)

def upload():
    '''上传代码到云服务器'''
    with SCPClient(ssh.get_transport()) as scp:
        scp_upload_folder(os.path.join(current_dir_path, "../"), server_folder, scp)

def build():
    commands = f"""
    cd {server_folder}/deploy;
    docker-compose -p {image_prefix} up -d --build
    """
    command_log(ssh.exec_command(commands))

    
if __name__=="__main__":
    host = "anesthesia.chat"
    username='root'
    server_folder = "~/kgvis"
    # docker镜像前缀
    image_prefix = "anesthsia-kg"

    current_dir_path = os.path.dirname(__file__) 

    # 创建SSH客户端
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    # 连接到远程服务器
    ssh.connect(hostname=host, port=22, username=username)

    clear()
    upload()
    build()
    
    # 关闭连接
    ssh.close()